package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.AlertParameters;
import model.CustomInfo;
import model.User;
import model.UserEventDetail;
import service.MonitorService;
import service.MonitorServiceImpl;
import thread.ThreadController;
import utils.RequestUtil;
import utils.msg.ComplexPollingRunnable;
import utils.msg.PollingQueryRunnable;
import dao.AlertParametersDao;
import dao.CustomInfoDao;
import dao.EventFieldsConditionDao;
import dao.UserEventDao;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet(description = "AdminServlet", urlPatterns = { "/AdminServlet" })
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	EventFieldsConditionDao efcDao = new EventFieldsConditionDao();
	CustomInfoDao ciDao = new CustomInfoDao();
	AlertParametersDao apDao = new AlertParametersDao();
	MonitorService mService;
	UserEventDao ueDao;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = RequestUtil.get(request.getParameter("method"));
		if(method.equals("getCustomInfoList")) {
			getCustomInfoList(request, response);
		} else if(method.equals("startThread")) {
			startThread(request, response);
		} else if(method.equals("stopThread")) {
			stopThread(request, response);
		} else if(method.equals("getStartInfoList")) {
			getStartInfoList(request, response);
		}else if(method.equals("getnonStartInfoList")) {
			getnonStartInfoList(request, response);
		}else if(method.equals("getUserEventInfoList")){
			getUserEventInfoList(request, response);
		}else if(method.equals("delefc")){
			delefc(request, response);
		}else if(method.equals("delUe")){
			delUe(request, response);
		}else if (method.equals("search")) {
			searchCustomInfo(request, response);
		}
		
	}









	private void stopThread(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("..........stopThread..........");
		String ueId = RequestUtil.get(request.getParameter("ueId"));
	
		ServletContext application=this.getServletContext();  
		@SuppressWarnings("unchecked")
		Map<Integer, ComplexPollingRunnable> map = (Map<Integer, ComplexPollingRunnable>) application.getAttribute("map");
		//容错处理，若线程未开启而执行以下代码，程序会出错
		if(map.containsKey(Integer.parseInt(ueId))){
			ComplexPollingRunnable pq = map.get(Integer.parseInt(ueId));
		pq.stopPolling();
		map.remove(Integer.parseInt(ueId)); //之前少了强制转换
		}
		
		@SuppressWarnings("unchecked")
		List<CustomInfo> infoList = (List<CustomInfo>) request.getSession().getAttribute("infoList");

		request.getSession().setAttribute("infoList", infoList);
		displayInfoList(request, response, infoList);
			
	}
	
	private void startThread(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String ueId = RequestUtil.get(request.getParameter("ueId"));
		ServletContext application=this.getServletContext();  
		@SuppressWarnings("unchecked")
		Map<Integer, ComplexPollingRunnable> map = (Map<Integer, ComplexPollingRunnable>) application.getAttribute("map");
		if(map.containsKey(ueId)){
			return;
		}
		ueDao = new UserEventDao();
		UserEventDetail ued = ueDao.getUserEventDetailById(Integer.parseInt(ueId));
		int count = efcDao.getEventFieldCondition(ued.getUserEvent().getId()+"");
		if(count!=0){//如果该事件没有条件，则不查询
			String sender = "【IUE】";
			ComplexPollingRunnable cpr = ThreadController.sendMsg(ued, sender);
			
			map.put(Integer.parseInt(ueId), cpr);
		}
		@SuppressWarnings("unchecked")
		List<CustomInfo> infoList = (List<CustomInfo>) request.getSession().getAttribute("infoList");
		displayInfoList(request, response, infoList);
		
	}
	
	@Deprecated
	private void oldStartThread(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("..........startThread..........");
		AlertParameters ap = null;
		String ueId = RequestUtil.get(request.getParameter("ueId"));
		ServletContext application=this.getServletContext();  
		@SuppressWarnings("unchecked")
		Map<Integer, PollingQueryRunnable> map = (Map<Integer, PollingQueryRunnable>) application.getAttribute("map");
		if(map.containsKey(ueId)){
			return;
		}
		ap = apDao.getAlertParameters(ueId);
		PollingQueryRunnable pq = ThreadController.sendMsg(ap);
		ueDao = new UserEventDao();
		//UserEventDetail ueDetail = ueDao.getUserEventDetailById(Integer.parseInt(ueId));
		
		map.put(Integer.parseInt(ueId), pq);
		@SuppressWarnings("unchecked")
		List<CustomInfo> infoList = (List<CustomInfo>) request.getSession().getAttribute("infoList");
		displayInfoList(request, response, infoList);
	}
	
	/**
	 * 获取所有定制的监听行为
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getCustomInfoList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println(".........getCustomInfoList........");
		List<CustomInfo> infoList = ciDao.getCustomInfoList();//从数据库获取数据
		request.getSession().setAttribute("infoList", infoList);
		displayInfoList(request, response, infoList);
	}
	
	/**
	 * 获取所有用UserEvent信息，并显示起包含的eventFieldCondition
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getUserEventInfoList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//你需要增加的代码，仿照getCustomInfoList方法
		//1.从数据库获取数据代码
		List<CustomInfo> infoList = ciDao.getCustomInfoList();//从数据库获取数据，这边需要自己修改
		request.getSession().setAttribute("infoList", infoList);
		displayUserEventInfoList(request, response, infoList);
	}
	
	private void getStartInfoList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ServletContext application=this.getServletContext();  
		@SuppressWarnings("unchecked")
		Map<Integer, PollingQueryRunnable> map = (Map<Integer, PollingQueryRunnable>) application.getAttribute("map");
		List<CustomInfo> infoList = ciDao.getStartInfoList(map);//从数据库获取数据
		request.getSession().setAttribute("infoList", infoList);
		displayInfoList(request, response, infoList);
	}
	private void getnonStartInfoList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ServletContext application=this.getServletContext();  
		@SuppressWarnings("unchecked")
		Map<Integer, PollingQueryRunnable> map = (Map<Integer, PollingQueryRunnable>) application.getAttribute("map");
		List<CustomInfo> infoList = ciDao.getnonStartInfoList(map);//从数据库获取数据
		request.getSession().setAttribute("infoList", infoList);
		displayInfoList(request, response, infoList);
	}
	
	private void displayUserEventInfoList(HttpServletRequest request,
			HttpServletResponse response, List<CustomInfo> infoList)
			throws ServletException, IOException {
		request.setAttribute("infoList", infoList);
		request.setAttribute("mainPage", "eventInfoList.jsp");//用来显示infoList
		request.getRequestDispatcher("eventManage.jsp").forward(request, response);
	}
	
	private void displayInfoList(HttpServletRequest request,
			HttpServletResponse response, List<CustomInfo> infoList)
			throws ServletException, IOException {
		request.setAttribute("infoList", infoList);
		request.setAttribute("mainPage", "monitorInfoList.jsp");//用来显示infoList
		request.getRequestDispatcher("monitorManage.jsp").forward(request, response);
	}
	
	private void delefc(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException{
		    String ueId = RequestUtil.get(request.getParameter("ueId"));
			ueDao = new UserEventDao();
			int result = -1;
			result = ueDao.deletefc(ueId);
	}
	
	private void delUe(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
	    String ueId = RequestUtil.get(request.getParameter("ueId"));
		ueDao = new UserEventDao();
		EventFieldsConditionDao efcDao = new EventFieldsConditionDao();
		int result = -1;
		if (efcDao.getEventFieldCondition(ueId) == 1) {
			request.setAttribute("exist", "eventManage.jsp");
		} else {
			result = ueDao.delUe(ueId);
			if (result >= 1) {
				request.setAttribute("succeed", "eventManage.jsp");
			} else {
				request.setAttribute("fail", "eventManage.jsp");
			}
		}
	    getUserEventInfoList(request,response);
	    System.out.println("servelt.delUe"+ueId);

	}
	
	private void searchCustomInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String info = RequestUtil.get(request.getParameter("info"));
		List<CustomInfo> infoList = ciDao.getserchCustomInfo(info);
		System.out.println(infoList.toString());
		request.setAttribute("infoList", infoList);
		request.setAttribute("mainPage", "eventInfoList.jsp");
		try {
			request.getRequestDispatcher("eventManage.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
		displayUserEventInfoList(request, response, infoList);
		
	}
	
	
}
